<template>
  <view class="register-container">
    <!-- 顶部装饰元素 -->
    <view class="top-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
    </view>
    
    <!-- 注册卡片 -->
    <scroll-view class="register-card" scroll-y="true" :style="{height: scrollHeight + 'px'}">
      <!-- 应用标题 -->
      <view class="app-header">
        <view class="app-logo">
          <image src="/static/logo.png" mode="aspectFit" />
        </view>
        <text class="app-title">注册账号</text>
        <text class="app-subtitle">加入景点旅游助手，开启旅程</text>
      </view>
      
      <!-- 注册表单 -->
      <view class="form-container">
        <view class="form-item">
          <text class="form-label">用户名</text>
          <input 
            class="form-input" 
            :class="{ 'error': errors.username }"
            type="text" 
            placeholder="请输入3-20位用户名" 
            v-model="formData.username"
            maxlength="20"
            @blur="validateUsername"
          />
          <text v-if="errors.username" class="error-text">{{ errors.username }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">邮箱</text>
          <input 
            class="form-input" 
            :class="{ 'error': errors.email }"
            type="text" 
            placeholder="请输入邮箱地址" 
            v-model="formData.email"
            @blur="validateEmail"
          />
          <text v-if="errors.email" class="error-text">{{ errors.email }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">设置密码</text>
          <input 
            class="form-input" 
            :class="{ 'error': errors.password }"
            type="password" 
            placeholder="请输入6-20位密码" 
            v-model="formData.password"
            @blur="validatePassword"
          />
          <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">确认密码</text>
          <input 
            class="form-input" 
            :class="{ 'error': errors.confirmPassword }"
            type="password" 
            placeholder="请再次输入密码" 
            v-model="formData.confirmPassword"
            @blur="validateConfirmPassword"
          />
          <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>
        </view>
        
        <view class="agreement">
          <label class="agreement-checkbox">
            <checkbox-group @change="agreementChange">
              <checkbox value="agree" :checked="agree" color="#2ecc71" />
            </checkbox-group>
            <text>我已阅读并同意</text>
          </label>
          <text class="agreement-link" @click="navigateToAgreement">《用户协议》</text>
          <text>和</text>
          <text class="agreement-link" @click="navigateToPrivacy">《隐私政策》</text>
        </view>
        
        <button 
          class="register-btn" 
          :disabled="loading || !isFormValid" 
          @click="handleRegister"
        >
          {{ loading ? '注册中...' : '立即注册' }}
        </button>
      </view>
      
      <!-- 已有账号链接 -->
      <view class="login-link">
        <text>已有账号？</text>
        <text class="login-text" @click="navigateToLogin">立即登录</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const formData = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const errors = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const agree = ref(false)
const loading = ref(false)
const scrollHeight = ref(500)

// 计算属性：表单是否有效
const isFormValid = computed(() => {
  return formData.value.username && 
         formData.value.email && 
         formData.value.password && 
         formData.value.confirmPassword &&
         !errors.value.username &&
         !errors.value.email &&
         !errors.value.password &&
         !errors.value.confirmPassword &&
         agree.value
})

onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = systemInfo.windowHeight - 80
})

// 验证函数
const validateUsername = () => {
  const username = formData.value.username.trim()
  if (!username) {
    errors.value.username = '用户名不能为空'
  } else if (username.length < 3 || username.length > 20) {
    errors.value.username = '用户名长度应为3-20位'
  } else {
    errors.value.username = ''
  }
}

const validateEmail = () => {
  const email = formData.value.email.trim()
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!email) {
    errors.value.email = '邮箱不能为空'
  } else if (!emailRegex.test(email)) {
    errors.value.email = '请输入正确的邮箱格式'
  } else {
    errors.value.email = ''
  }
}

const validatePassword = () => {
  const password = formData.value.password
  if (!password) {
    errors.value.password = '密码不能为空'
  } else if (password.length < 6 || password.length > 20) {
    errors.value.password = '密码长度应为6-20位'
  } else {
    errors.value.password = ''
  }
}

const validateConfirmPassword = () => {
  const confirmPassword = formData.value.confirmPassword
  if (!confirmPassword) {
    errors.value.confirmPassword = '请确认密码'
  } else if (confirmPassword !== formData.value.password) {
    errors.value.confirmPassword = '两次输入的密码不一致'
  } else {
    errors.value.confirmPassword = ''
  }
}

const agreementChange = (e) => {
  // 修正这里，Uni-app checkbox-group change 事件返回的是 detail.value 数组
  agree.value = e.detail.value.includes('agree')
}

const request = async (options) => {
  try {
    const res = await uni.request({
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      }
    })

    // HBuilderX 3.7+ 返回对象，cli 可能返回数组
    let response = res
    if (Array.isArray(res)) {
      response = res[1] || res[0]
    }

    if (!response) {
      throw new Error('无响应数据')
    }

    if (response.statusCode >= 400) {
      const errorMsg = response.data?.message ||
                       response.data?.error ||
                       `请求失败: ${response.statusCode}`
      throw new Error(errorMsg)
    }

    return response.data
  } catch (error) {
    console.error('请求异常:', error)
    throw new Error(error.message || '服务器异常，请稍后重试')
  }
}

const handleRegister = async () => {
  // 验证逻辑
  validateUsername()
  validateEmail()
  validatePassword()
  validateConfirmPassword()

  if (!isFormValid.value) {
    uni.showToast({
      title: '请检查输入信息',
      icon: 'none'
    })
    return
  }

  loading.value = true
  uni.showLoading({ title: '注册中...' })

  try {
    const response = await request({
      url: 'http://192.168.165.171:8080/api/users/register',
      method: 'POST',
      data: {
        username: formData.value.username.trim(),
        password: formData.value.password,
        email: formData.value.email.trim()
      }
    })

    uni.showToast({
      title: '注册成功',
      icon: 'success'
    })
    
    // 注册成功后跳转逻辑
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }, 1500)
  } catch (error) {
    console.error('注册失败:', error)
    uni.showToast({
      title: error.message,
      icon: 'none',
      duration: 3000
    })
  } finally {
    loading.value = false
    uni.hideLoading()
  }
}

const navigateToAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/index'
  })
}

const navigateToPrivacy = () => {
  uni.navigateTo({
    url: '/pages/privacy/index'
  })
}

const navigateToLogin = () => {
  uni.navigateBack()
}
</script>

<style lang="scss">
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #3498db, #2ecc71);
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.top-decoration {
  position: absolute;
  top: -100rpx;
  right: -100rpx;
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  
  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
  
  .circle-1 {
    width: 200rpx;
    height: 200rpx;
    top: 50rpx;
    left: -100rpx;
  }
  
  .circle-2 {
    width: 150rpx;
    height: 150rpx;
    top: 150rpx;
    left: -50rpx;
  }
}

.register-card {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  margin-top: 60rpx;
  width: 100%;
  box-sizing: border-box;
}

.app-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
  
  .app-logo {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #3498db, #2ecc71);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 15rpx;
    
    image {
      width: 50rpx;
      height: 50rpx;
    }
  }
  
  .app-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .app-subtitle {
    font-size: 22rpx;
    color: #999;
  }
}

.form-container {
  .form-item {
    margin-bottom: 30rpx;
    
    .form-label {
      display: block;
      font-size: 26rpx;
      color: #666;
      margin-bottom: 12rpx;
      font-weight: 500;
    }
    
    .form-input {
      width: 100%;
      height: 70rpx;
      border: 2rpx solid #eee;
      border-radius: 10rpx;
      padding: 0 20rpx;
      font-size: 26rpx;
      background-color: #f9f9f9;
      max-width: 600rpx;
      box-sizing: border-box;
      
      &:focus {
        border-color: #3498db;
      }
      
      &.error {
        border-color: #e74c3c;
      }
    }
    
    .error-text {
      display: block;
      font-size: 20rpx;
      color: #e74c3c;
      margin-top: 8rpx;
    }
  }
}

.agreement {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 30rpx;
  line-height: 1.4;
  
  .agreement-checkbox {
    display: flex;
    align-items: center;
    
    checkbox {
      transform: scale(0.7);
      margin-right: 6rpx;
    }
  }
  
  .agreement-link {
    color: #3498db;
    margin: 0 6rpx;
  }
}

.register-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(135deg, #3498db, #2ecc71);
  color: #fff;
  border-radius: 10rpx;
  font-size: 30rpx;
  font-weight: 500;
  border: none;
  margin-bottom: 30rpx;
  
  &:active {
    opacity: 0.9;
  }
  
  &[disabled] {
    opacity: 0.7;
    background: #ccc;
  }
}

.login-link {
  text-align: center;
  font-size: 24rpx;
  color: #666;
  
  .login-text {
    color: #3498db;
    margin-left: 8rpx;
  }
}
</style>